package org.school.streaming.net.client.listeners;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;

import org.school.streaming.net.client.Client;
import org.school.streaming.net.client.ClientFrame;
import org.school.streaming.net.client.packets.RTPPacket;

/**
 * @authors Jeffrey Goudzwaard,
 * 			Davin Terrizzi
 * @version	1.0
 * @date	18-4-2013
 */

/**
 * Class representing code behind Timer of Client
 * 
 * @author Davin
 * 
 */
public class timerListener implements ActionListener {
	@Override
	public void actionPerformed(ActionEvent ae) {

		// Get Client instance
		Client client = Client.getClient();

		// Set client UDP packet to new sever-sent packet
		client.setDatagramPacket(new DatagramPacket(client.getBuffer(), client.getBuffer().length));

		try {
			// If UDP packet received succesfully ...
			client.getDatagramSocket().receive(client.getDatagramPacket());

			// ... create RTP packet
			RTPPacket packet = new RTPPacket(client.getDatagramPacket().getData(), client.getDatagramPacket().getLength());

			// Log RTP data
			System.out.println("Got RTP packet with SeqNum # " + packet.getSequenceNumber() + " TimeStamp " + packet.getTimeStamp() + " ms, of type "
					+ packet.getPayloadType());
			packet.printHeader();

			// Dissolve RTP packet to get payload data
			int payloadLength = packet.getPayloadLength();
			byte[] payload = new byte[payloadLength];
			packet.getPayload(payload);

			// Update Client GUI with payload data
			Toolkit toolkit = Toolkit.getDefaultToolkit();
			Image image = toolkit.createImage(payload, 0, payloadLength);
			ClientFrame.setIcon(image);
		} catch (InterruptedIOException e) {
			// System.err.println( "Nothing to read!" );
		} catch (IOException e) {
			System.err.println(e);
		}

	}
}
